package com.aimashi.lambadalearning.distinct;

import com.aimashi.lambadalearning.entity.GoodInfo;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class Demo {
  public static void main(String[] args) {
    List<GoodInfo> goodInfos = Arrays.asList();
    goodInfos.add(new GoodInfo("tb", "tb_1112312312", 199, 100000));
    goodInfos.add(new GoodInfo("tb", "tb_23534231231", 399, 10));
    goodInfos.add(new GoodInfo("jd", "jd_1110080098", 299, 100));
    goodInfos.add(new GoodInfo("jd", "jd_1110080098", 299, 100));
    goodInfos.add(new GoodInfo("jd", "jd_412313123", 99, 10000000));
    goodInfos.add(new GoodInfo("pdd", "pdd_354532431", 599, 1));
    goodInfos.add(new GoodInfo("pdd", "pdd_1423124131", 499, 10));

    // 使用treeset 集合来实现去重，这里一定要使用集合接收，不然等于没有去重
    List<GoodInfo> goodInfos1 =
        goodInfos.stream()
            .collect(
                Collectors.collectingAndThen(
                    Collectors.toCollection(
                        () -> new TreeSet<>(Comparator.comparing(o -> o.getSkuNo()))),
                    ArrayList::new));

    // 使用map去重
    List<GoodInfo> goodInfos2 =
        goodInfos.stream()
            .filter(distinctByKey(goodInfo -> goodInfo.getSkuNo()))
            .collect(Collectors.toList());
  }

  public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
    Map<Object, Boolean> seen = new ConcurrentHashMap<>();
    return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
  }
}
